<template>
  <CommonLayout default-active-menu="/home">
    <h2 class="page-title">我的仪表盘</h2>
    
    <!-- 统计数据卡片 -->
    <div class="stat-cards">
      <el-card class="stat-card">
        <template #header>
          <div class="card-header">
            <span>总面试次数</span>
            <el-icon><Calendar /></el-icon>
          </div>
        </template>
        <div class="card-value">{{ statistics.totalInterviews }}</div>
      </el-card>
      
      <el-card class="stat-card">
        <template #header>
          <div class="card-header">
            <span>待面试数</span>
            <el-icon><Timer /></el-icon>
          </div>
        </template>
        <div class="card-value">{{ statistics.pendingInterviews }}</div>
      </el-card>
      
      <el-card class="stat-card">
        <template #header>
          <div class="card-header">
            <span>平均分数</span>
            <el-icon><StarFilled /></el-icon>
          </div>
        </template>
        <div class="card-value">{{ statistics.averageScore }}</div>
      </el-card>
    </div>
    
    <!-- 成绩折线图 -->
    <el-card class="chart-card">
      <template #header>
        <div class="card-header">
          <span>历史面试成绩走势</span>
        </div>
      </template>
      <div ref="chartRef" class="chart-container"></div>
    </el-card>
    
    <!-- 最近面试列表 -->
    <el-card class="recent-interviews">
      <template #header>
        <div class="card-header">
          <span>最近面试记录</span>
          <el-button type="primary" text @click="viewAllHistory">查看所有</el-button>
        </div>
      </template>
      <el-table :data="recentInterviews" style="width: 100%">
        <el-table-column prop="name" label="公司" />
        <el-table-column prop="job_title" label="职位" />
        <el-table-column prop="created_at" label="面试日期" sortable width="190" >
          <template #default="scope">
            {{ formatDate(scope.row.created_at) }}
          </template>
        </el-table-column>
        <el-table-column prop="total_score" label="得分">
          <template #default="scope">
            <el-tag :type="getScoreTagType(scope.row.scototal_scorere)">{{ scope.row.total_score }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="type" label="面试结果" width="180" >
          <template #default="scope">
            {{ getResultTag(scope.row.total_score) }}
          </template>
        </el-table-column>
      </el-table>
    </el-card>
  </CommonLayout>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import * as echarts from 'echarts';
import { Calendar, Timer, StarFilled } from '@element-plus/icons-vue';
import CommonLayout from '@/components/CommonLayout.vue';
import { getHistoryInfo,getInterviewInfo } from '@/api/home';
import { format } from 'date-fns';

const router = useRouter();
const chartRef = ref<HTMLElement | null>(null);
let chart: echarts.ECharts | null = null;



// 模拟的最近面试数据
const recentInterviews = ref([
  { id: 1, date: '2023-12-05', position: '前端开发工程师', company: '腾讯科技', score: 88 },
  { id: 2, date: '2023-11-20', position: 'Web开发工程师', company: '阿里巴巴', score: 92 },
  { id: 3, date: '2023-11-10', position: '全栈开发工程师', company: '字节跳动', score: 78 },
  { id: 4, date: '2023-10-28', position: 'Vue开发工程师', company: '百度', score: 85 }
]);

// 模拟的历史分数数据 - 用于图表
const historicalScores = ref();



// 根据分数返回不同的标签类型
const getScoreTagType = (score: number) => {
  if (score >= 90) return 'success';
  if (score >= 80) return 'warning';
  if (score >= 70) return 'info';
  return 'danger';
};

const getResultTag = (result: number) => {
  if(result>=60){
    return '通过'
  }
  return '未通过'
}

const formatDate = (date: string) => {
  if(date==undefined){
    return ''
  }
  return format(new Date(date), 'yyyy-MM-dd');
};

// 查看所有历史记录
const viewAllHistory = () => {
  router.push('/interview-history');
};

// 查看面试详情
const viewDetail = (id: number) => {
  router.push(`/interview-detail/${id}`);
};

// 初始化图表
const initChart = () => {
  if (chartRef.value) {
    chart = echarts.init(chartRef.value);
    const option = {
      tooltip: {
        trigger: 'axis'
      },
      grid: {
        left: '3%',
        right: '4%',
        bottom: '3%',
        containLabel: true
      },
      xAxis: {
        type: 'category',
        boundaryGap: false,
        data: historicalScores.value.map(item => item.date)
      },
      yAxis: {
        type: 'value',
        min: 60,
        max: 100
      },
      series: [
        {
          name: '面试分数',
          type: 'line',
          data: historicalScores.value.map(item => item.score),
          smooth: true,
          lineStyle: {
            color: '#1890ff',
            width: 3
          },
          symbol: 'circle',
          symbolSize: 8,
          itemStyle: {
            color: '#1890ff'
          },
          areaStyle: {
            color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
              {
                offset: 0,
                color: 'rgba(24,144,255,0.3)'
              },
              {
                offset: 1,
                color: 'rgba(24,144,255,0.1)'
              }
            ])
          }
        }
      ]
    };
    chart.setOption(option);
    
    // 响应窗口大小变化
    window.addEventListener('resize', () => {
      chart?.resize();
    });
  }
};
let userId = localStorage.getItem('userid')
  // 统计数据
  let statistics = reactive({
    totalInterviews: 0,
    pendingInterviews: 0,
    averageScore: 0
  });
onMounted( async() => {
  
  let response = await getInterviewInfo(userId)
  let responseHis = await getHistoryInfo(userId)
  statistics.totalInterviews = response.interviewed_count || 0
  statistics.pendingInterviews = response.pending_count || 0
  statistics.averageScore = response.avg_score || 0
  historicalScores.value=response.score_history
  recentInterviews.value = responseHis.history
  initChart();
});
</script>

<style scoped>
.page-title {
  margin-top: 0;
  margin-bottom: 20px;
  font-size: 20px;
  color: #333;
}

.stat-cards {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 20px;
  margin-bottom: 20px;
}

.stat-card {
  text-align: center;
  height: 100%;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-value {
  font-size: 32px;
  font-weight: bold;
  color: #1890ff;
  margin: 10px 0;
}

.chart-card {
  margin-bottom: 20px;
}

.chart-container {
  height: 350px;
  width: 100%;
}

.recent-interviews {
  margin-bottom: 20px;
}

/* 媒体查询适配不同屏幕尺寸 */
@media screen and (max-width: 768px) {
  .stat-cards {
    grid-template-columns: repeat(2, 1fr);
  }
  
  .chart-container {
    height: 280px;
  }
}

@media screen and (max-width: 576px) {
  .stat-cards {
    grid-template-columns: 1fr;
  }
  
  .chart-container {
    height: 250px;
  }
}
</style>
